#!/usr/bin/env node

const http=require('http'),
      url=require('url'),
      qs=require('querystring'),
      log=console.log;

let items=[];

http.createServer((req,res)=>{
  if(req.url!='/'){
    err(res);
    return;
  }
  
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log(req.headers);
  log('');

  switch(req.method){
    case 'GET':
      showHtml(res);
      break;
    case 'POST':
      addItem(req,res);
      break;
    default:
      err(res);
      break;
  }

}).listen(8080);


function addItem(req,res){
  let body='';

  req.on('data',chunk=>body+=chunk);
  req.on('end',()=>{
    log(body);
    let item=qs.parse(body).item;
    if(item!=='')items.push(item);
    
    log(items);
    showHtml(res);
  
  })
}



function showHtml(res){
  let html=`
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset='utf8'/>
      <title>todolist</title>
    </head>
    <body>
      <h1>Todolist</h1>
      <form method='post' action='/'>
        <input type='text' name='item' />
        <input type='submit' value='addItem' />
      </form>
      <ul>
        ${items.map(item=>'<li>'+item+'</li>').join('')}
      </ul>
    </body>
  </html>`;

  res.setHeader('Content-Type','text/html');
  res.setHeader('Content-Length',Buffer.byteLength(html));
  
  res.statusCode=200;
  res.end(html);

}


function err(res){
  const msg = 'Not found!';

  res.statusCode = 404;
  res.setHeader('Content-Length', msg.length);
  res.setHeader('Content-Type', 'text/plain');

  res.end(msg);
}
